/*
 * @Author       : huangzb
 * @Date         : 2024-01-18 09:48:59
 * @LastEditors  : huangzb
 * @LastEditTime : 2024-01-24 15:27:40
 * @Description  : file content
 * @FilePath     : \Interface\app\middleware\jwtErr.js
 */
const { failRes } = require("../extend/helper");
const { whitelist } = require("../extend/local");
const { Journal } = require("../exception/Journal");

function filterWhitelist(url) {
  let flag = false;
  whitelist &&
    whitelist.forEach(item => {
      if (url.indexOf(item) >= 0) flag = true;
    });
  return flag;
}

module.exports = () => {
  return async function jwtErr(ctx, next) {
    try {
      const { url } = ctx.request;
      console.log('filterWhitelist(url): ', filterWhitelist(url), url);
      if (filterWhitelist(url)) {
        console.log("url jwtErr: ", url);
        await next();
      } else if (ctx?.request?.method === "OPTIONS") {
        ctx.status = 204;
      } else {
        const authorization = ctx.request.headers.authorization;
        if (authorization !== "null" && authorization) {
          const token = authorization.split(" ")[1];
          const decoded =
            (await ctx.app.jwt.verify(
              token,
              ctx?.app?.config?.jwt?.secret ?? ""
            )) || "false"; // 解密token

          if (decoded !== "false") {
            // token 未过期
            await next();
          } else {
            // token 已过期，请重新登录
            await Journal(ctx, { operatorType: "系统拦截", code: 101 });
            ctx.status = 500;
            ctx.body = failRes(101);
          }
        } else {
          if (url.indexOf("/public/upload/") >= 0) { // 如果是访问图片资源，就不拦截
            await next();
          }else{
            // token 不存在
            await Journal(ctx, { operatorType: "系统拦截", code: 102 });
            ctx.status = 500;
            ctx.body = failRes(102);
          }
        }
      }
    } catch (error) {
      console.log("error - jwt: ", error);
      if (typeof error === "object" && error.message === "jwt expired") {
        ctx.status = 500;
        ctx.body = failRes(101);
      }
    }
  };
};
